package xyz.hubery.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collections;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import xyz.hubery.domain.SysRolePrivilege;
import xyz.hubery.mapper.SysPrivilegeMapper;
import xyz.hubery.domain.SysPrivilege;
import xyz.hubery.service.SysPrivilegeService;
import xyz.hubery.service.SysRolePrivilegeService;

@Service
public class SysPrivilegeServiceImpl extends ServiceImpl<SysPrivilegeMapper, SysPrivilege> implements SysPrivilegeService{

    @Autowired
    private SysRolePrivilegeService rolePrivilegeService;

    @Override
    public List<SysPrivilege> findPrivilegeByRoleId(Long roleId) {

        // 查询所有权限
        List<SysPrivilege> privileges = this.list();
        // 为该角色的权限添加标识
        for (SysPrivilege privilege : privileges) {
            if(isRolePrivilege(privilege.getId(),roleId)){
                privilege.setOwn(1);
            }
        }

        return privileges;
    }

    private boolean isRolePrivilege(Long privilegeId, Long roleId) {
        SysRolePrivilege rolePrivilege = rolePrivilegeService.getOne(new LambdaQueryWrapper<SysRolePrivilege>().eq(SysRolePrivilege::getPrivilegeId, privilegeId).eq(SysRolePrivilege::getRoleId, roleId));
        return rolePrivilege != null;
    }
}
